'use client';

import React, { useEffect, useState } from 'react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, PieChart, Pie, Cell } from 'recharts';
import { Card, CardContent, Typography, Grid, Box } from '@mui/material';
import { getExamStatistics } from '../api/exam';

interface ExamStatisticsProps {
  examId: number;
}

interface StatisticsData {
  scoreDistribution: { score: number; count: number }[];
  passRate: number;
  averageScore: number;
  totalStudents: number;
  highestScore: number;
  lowestScore: number;
}

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8'];

export default function ExamStatistics({ examId }: ExamStatisticsProps) {
  const [statistics, setStatistics] = useState<StatisticsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchStatistics = async () => {
      try {
        const data = await getExamStatistics(examId);
        setStatistics(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : '获取统计数据失败');
      } finally {
        setLoading(false);
      }
    };

    fetchStatistics();
  }, [examId]);

  if (loading) return <div>加载中...</div>;
  if (error) return <div>错误: {error}</div>;
  if (!statistics) return <div>暂无数据</div>;

  const passRateData = [
    { name: '及格', value: statistics.passRate },
    { name: '不及格', value: 100 - statistics.passRate }
  ];

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom>考试统计分析</Typography>
      
      <Grid container spacing={3}>
        {/* 基础统计信息 */}
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>基本信息</Typography>
              <Typography>参考人数: {statistics.totalStudents}</Typography>
              <Typography>平均分: {statistics.averageScore.toFixed(2)}</Typography>
              <Typography>最高分: {statistics.highestScore}</Typography>
              <Typography>最低分: {statistics.lowestScore}</Typography>
              <Typography>及格率: {statistics.passRate.toFixed(2)}%</Typography>
            </CardContent>
          </Card>
        </Grid>

        {/* 成绩分布柱状图 */}
        <Grid item xs={12} md={8}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>成绩分布</Typography>
              <BarChart
                width={600}
                height={300}
                data={statistics.scoreDistribution}
                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="score" label={{ value: '分数段', position: 'insideBottom', offset: -5 }} />
                <YAxis label={{ value: '人数', angle: -90, position: 'insideLeft' }} />
                <Tooltip />
                <Legend />
                <Bar dataKey="count" fill="#8884d8" name="人数" />
              </BarChart>
            </CardContent>
          </Card>
        </Grid>

        {/* 及格率饼图 */}
        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>及格率分布</Typography>
              <PieChart width={400} height={300}>
                <Pie
                  data={passRateData}
                  cx={200}
                  cy={150}
                  innerRadius={60}
                  outerRadius={80}
                  fill="#8884d8"
                  paddingAngle={5}
                  dataKey="value"
                  label
                >
                  {passRateData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
                <Legend />
              </PieChart>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
}